from scipy import optimize
import numpy as np
import matplotlib.pyplot as plt

def fitfunc(p, x):
    """Function to be fitted.
        
        Arguments:
            
            - x - independent variable
            - p - tuple of parameters
    """
    return np.exp(-x/p[0])/p[1]

# simulate some data
n = 100
a, b = 0.1, 0.1
x = np.linspace(0, 1., n)
y = np.exp(-x/a)/b 

# add noise
y = y + np.random.randn(n)

# Define an error function (standard form)
errfunc = lambda p, x, y: (y - fitfunc(p, x))

# Initial values for fit parameters
pinit = np.array([2, 2])

out = optimize.leastsq(errfunc, pinit,args=(x, y),full_output = 1)
plt.plot(x, fitfunc(out[0], x),'r--',lw=2,label="Fit")
plt.plot(x, y,'o',label="Data")

plt.legend()
plt.show()
